<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message, Modal } from 'ant-design-vue';

import PerformanceStatisticsModal from './components/PerformanceStatisticsModal.vue';
import ScheduleManagementModal from './components/ScheduleManagementModal.vue';
import TechnicianDetailModal from './components/TechnicianDetailModal.vue';
// 导入模态框组件
import TechnicianFormModal from './components/TechnicianFormModal.vue';

// 技师接口定义
interface Technician {
  id: string;
  name: string;
  avatar?: string;
  gender: 'female' | 'male';
  phone: string;
  email?: string;
  department: string;
  position: string;
  level: '专家' | '中级' | '初级' | '高级';
  status: 'active' | 'inactive' | 'training';
  hireDate: string;
  skills: string[];
  performance: {
    income: number;
    score: number;
    services: number;
  };
  schedule: {
    workDays: string[];
    workTime: string;
  };
  notes?: string;
}

// 响应式数据
const loading = ref(false);
const selectedTechnician = ref<null | Technician>(null);

// 筛选条件
const filters = ref({
  department: '',
  status: '',
  level: '',
  search: '',
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 模态框状态
const modals = ref({
  technicianForm: false,
  technicianDetail: false,
  scheduleManagement: false,
  performanceStatistics: false,
});

// 技师数据
const technicians = ref<Technician[]>([
  {
    id: 'T001',
    name: '王雨然',
    avatar: '',
    gender: 'female',
    phone: '13800138001',
    email: 'wangyuran@example.com',
    department: '按摩部',
    position: '高级按摩师',
    level: '高级',
    status: 'active',
    hireDate: '2023-01-15',
    skills: ['泰式按摩', '经脉按摩', '正骨按摩', '头皮按摩'],
    performance: {
      score: 4.8,
      services: 156,
      income: 15_600,
    },
    schedule: {
      workDays: ['周一', '周二', '周三', '周四', '周五'],
      workTime: '09:00-18:00',
    },
    notes: '技术精湛，客户满意度高',
  },
  {
    id: 'T002',
    name: '李小明',
    avatar: '',
    gender: 'male',
    phone: '13800138002',
    email: 'lixiaoming@example.com',
    department: '按摩部',
    position: '按摩师',
    level: '中级',
    status: 'active',
    hireDate: '2023-03-20',
    skills: ['泰式按摩', '经脉按摩'],
    performance: {
      score: 4.5,
      services: 98,
      income: 9800,
    },
    schedule: {
      workDays: ['周二', '周三', '周四', '周五', '周六'],
      workTime: '10:00-19:00',
    },
  },
  {
    id: 'T003',
    name: '张美丽',
    avatar: '',
    gender: 'female',
    phone: '13800138003',
    email: 'zhangmeili@example.com',
    department: '美容部',
    position: '美容师',
    level: '专家',
    status: 'active',
    hireDate: '2022-08-10',
    skills: ['面部护理', '身体护理', 'SPA护理', '美甲'],
    performance: {
      score: 4.9,
      services: 203,
      income: 20_300,
    },
    schedule: {
      workDays: ['周一', '周二', '周三', '周四', '周五', '周六'],
      workTime: '09:00-18:00',
    },
    notes: '美容专家，技术一流',
  },
  // 生成更多技师数据
  ...Array.from({ length: 20 }, (_, i) => ({
    id: `T${String(i + 4).padStart(3, '0')}`,
    name: `技师${i + 4}`,
    avatar: '',
    gender: i % 2 === 0 ? 'female' : 'male',
    phone: `13800138${String(i + 4).padStart(3, '0')}`,
    email: `tech${i + 4}@example.com`,
    department: i % 3 === 0 ? '按摩部' : i % 3 === 1 ? '美容部' : 'SPA部',
    position: i % 3 === 0 ? '按摩师' : i % 3 === 1 ? '美容师' : 'SPA师',
    level: ['初级', '中级', '高级', '专家'][i % 4] as any,
    status: ['active', 'active', 'active', 'training'][i % 4] as any,
    hireDate: `2023-${String(Math.floor(i / 12) + 1).padStart(2, '0')}-${String((i % 28) + 1).padStart(2, '0')}`,
    skills: ['泰式按摩', '经脉按摩', '面部护理', '身体护理'].slice(
      0,
      (i % 4) + 1,
    ),
    performance: {
      score: 4 + (i % 10) * 0.1,
      services: 50 + i * 5,
      income: 5000 + i * 500,
    },
    schedule: {
      workDays: ['周一', '周二', '周三', '周四', '周五'],
      workTime: '09:00-18:00',
    },
  })),
]);

// 表格列定义
const columns = [
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 60,
  },
  {
    title: '技师编号',
    dataIndex: 'id',
    key: 'id',
    width: 100,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 60,
    customRender: ({ text }: any) => (text === 'male' ? '男' : '女'),
  },
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
    width: 100,
  },
  {
    title: '职位',
    dataIndex: 'position',
    key: 'position',
    width: 120,
  },
  {
    title: '等级',
    dataIndex: 'level',
    key: 'level',
    width: 80,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '技能',
    dataIndex: 'skills',
    key: 'skills',
    width: 200,
  },
  {
    title: '绩效',
    dataIndex: 'performance',
    key: 'performance',
    width: 150,
  },
  {
    title: '入职时间',
    dataIndex: 'hireDate',
    key: 'hireDate',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 计算属性
const filteredTechnicians = computed(() => {
  let filtered = technicians.value;

  // 部门筛选
  if (filters.value.department) {
    filtered = filtered.filter(
      (tech) => tech.department === filters.value.department,
    );
  }

  // 状态筛选
  if (filters.value.status) {
    filtered = filtered.filter((tech) => tech.status === filters.value.status);
  }

  // 等级筛选
  if (filters.value.level) {
    filtered = filtered.filter((tech) => tech.level === filters.value.level);
  }

  // 搜索筛选
  if (filters.value.search) {
    const query = filters.value.search.toLowerCase();
    filtered = filtered.filter(
      (tech) =>
        tech.name.toLowerCase().includes(query) ||
        tech.id.toLowerCase().includes(query) ||
        tech.phone.includes(query),
    );
  }

  return filtered;
});

// 统计数据
const statistics = computed(() => {
  const total = technicians.value.length;
  const active = technicians.value.filter(
    (tech) => tech.status === 'active',
  ).length;
  const onDuty = technicians.value.filter(
    (tech) => tech.status === 'active',
  ).length; // 简化处理
  const expert = technicians.value.filter(
    (tech) => tech.level === '专家',
  ).length;

  return { total, active, onDuty, expert };
});

// 方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'green',
    inactive: 'red',
    training: 'orange',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    active: '在职',
    inactive: '离职',
    training: '培训中',
  };
  return textMap[status] || status;
};

const getLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    初级: 'blue',
    中级: 'green',
    高级: 'orange',
    专家: 'purple',
  };
  return colorMap[level] || 'default';
};

const handleSearch = () => {
  pagination.value.current = 1;
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
};

const showAddModal = () => {
  selectedTechnician.value = null;
  modals.value.technicianForm = true;
};

const editTechnician = (technician: Technician) => {
  selectedTechnician.value = technician;
  modals.value.technicianForm = true;
};

const viewDetails = (technician: Technician) => {
  selectedTechnician.value = technician;
  modals.value.technicianDetail = true;
};

const viewSchedule = (technician: Technician) => {
  selectedTechnician.value = technician;
  modals.value.scheduleManagement = true;
};

const showScheduleModal = () => {
  modals.value.scheduleManagement = true;
};

const showPerformanceModal = () => {
  modals.value.performanceStatistics = true;
};

const resetPassword = (technician: Technician) => {
  Modal.confirm({
    title: '重置密码',
    content: `确定要重置技师 ${technician.name} 的密码吗？`,
    onOk: () => {
      message.success(`技师 ${technician.name} 的密码已重置`);
    },
  });
};

const viewPerformance = (technician: Technician) => {
  selectedTechnician.value = technician;
  modals.value.performanceStatistics = true;
};

const viewHistory = (technician: Technician) => {
  message.info(`查看技师 ${technician.name} 的服务记录`);
};

const deleteTechnician = (technician: Technician) => {
  Modal.confirm({
    title: '删除技师',
    content: `确定要删除技师 ${technician.name} 吗？此操作不可恢复。`,
    okType: 'danger',
    onOk: () => {
      const index = technicians.value.findIndex((t) => t.id === technician.id);
      if (index !== -1) {
        technicians.value.splice(index, 1);
        message.success(`技师 ${technician.name} 已删除`);
      }
    },
  });
};

const handleFormSuccess = () => {
  message.success('操作成功');
  modals.value.technicianForm = false;
  selectedTechnician.value = null;
};

const refreshData = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('数据已刷新');
  }, 1000);
};

const exportData = () => {
  message.success('数据导出成功');
};

// 生命周期
onMounted(() => {
  pagination.value.total = technicians.value.length;
});
</script>

<template>
  <div class="technician-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>技师管理</h2>
        <p>管理技师信息、排班安排、绩效统计</p>
      </div>
      <div class="header-actions">
        <a-button type="primary" @click="showAddModal"> ➕ 新增技师 </a-button>
        <a-button @click="exportData"> 📥 导出数据 </a-button>
      </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="部门">
            <a-select
              v-model:value="filters.department"
              placeholder="请选择部门"
              allow-clear
            >
              <a-select-option value="按摩部">按摩部</a-select-option>
              <a-select-option value="美容部">美容部</a-select-option>
              <a-select-option value="SPA部">SPA部</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="技师状态">
            <a-select
              v-model:value="filters.status"
              placeholder="请选择状态"
              allow-clear
            >
              <a-select-option value="active">在职</a-select-option>
              <a-select-option value="inactive">离职</a-select-option>
              <a-select-option value="training">培训中</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="技能等级">
            <a-select
              v-model:value="filters.level"
              placeholder="请选择等级"
              allow-clear
            >
              <a-select-option value="初级">初级</a-select-option>
              <a-select-option value="中级">中级</a-select-option>
              <a-select-option value="高级">高级</a-select-option>
              <a-select-option value="专家">专家</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="搜索">
            <a-input-search
              v-model:value="filters.search"
              placeholder="姓名/编号/手机号"
              @search="handleSearch"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: #1890ff">👤</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total }}</div>
                <div class="stat-label">总技师数</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: #52c41a">✅</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.active }}</div>
                <div class="stat-label">在职技师</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: #faad14">⏰</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.onDuty }}</div>
                <div class="stat-label">在岗技师</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: #722ed1">⭐</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.expert }}</div>
                <div class="stat-label">专家技师</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 技师列表 -->
    <div class="technician-list">
      <a-card title="技师列表" :bordered="false">
        <template #extra>
          <a-space>
            <a-button @click="refreshData"> 🔄 刷新 </a-button>
            <a-button @click="showScheduleModal"> 📅 排班管理 </a-button>
            <a-button @click="showPerformanceModal"> 📊 绩效统计 </a-button>
          </a-space>
        </template>

        <a-table
          :columns="columns"
          :data-source="filteredTechnicians"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'avatar'">
              <a-avatar :src="record.avatar" :alt="record.name">
                {{ record.name.charAt(0) }}
              </a-avatar>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'level'">
              <a-tag :color="getLevelColor(record.level)">
                {{ record.level }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'skills'">
              <a-space wrap>
                <a-tag
                  v-for="skill in record.skills.slice(0, 3)"
                  :key="skill"
                  size="small"
                >
                  {{ skill }}
                </a-tag>
                <a-tag v-if="record.skills.length > 3" size="small">
                  +{{ record.skills.length - 3 }}
                </a-tag>
              </a-space>
            </template>
            <template v-else-if="column.key === 'performance'">
              <div class="performance-info">
                <div class="performance-score">
                  {{ record.performance.score }}分
                </div>
                <div class="performance-detail">
                  <span>服务{{ record.performance.services }}次</span>
                  <span>收入{{ record.performance.income }}元</span>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button
                  type="link"
                  size="small"
                  @click="editTechnician(record)"
                >
                  编辑
                </a-button>
                <a-button type="link" size="small" @click="viewDetails(record)">
                  详情
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  @click="viewSchedule(record)"
                >
                  排班
                </a-button>
                <a-dropdown>
                  <a-button type="link" size="small"> 更多 ⬇️ </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="resetPassword(record)">
                        🔑 重置密码
                      </a-menu-item>
                      <a-menu-item @click="viewPerformance(record)">
                        📊 查看绩效
                      </a-menu-item>
                      <a-menu-item @click="viewHistory(record)">
                        📋 服务记录
                      </a-menu-item>
                      <a-menu-divider />
                      <a-menu-item danger @click="deleteTechnician(record)">
                        🗑️ 删除
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 新增/编辑技师模态框 -->
    <TechnicianFormModal
      v-model:visible="modals.technicianForm"
      :technician="selectedTechnician"
      @success="handleFormSuccess"
    />

    <!-- 技师详情模态框 -->
    <TechnicianDetailModal
      v-model:visible="modals.technicianDetail"
      :technician="selectedTechnician"
    />

    <!-- 排班管理模态框 -->
    <ScheduleManagementModal
      v-model:visible="modals.scheduleManagement"
      :technicians="technicians"
    />

    <!-- 绩效统计模态框 -->
    <PerformanceStatisticsModal
      v-model:visible="modals.performanceStatistics"
      :technicians="technicians"
    />
  </div>
</template>

<style scoped>
.technician-management {
  min-height: 100vh;
  padding: 24px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.header-left h2 {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.header-left p {
  margin: 0;
  color: #8c8c8c;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section {
  padding: 24px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.statistics-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.stat-content {
  display: flex;
  gap: 16px;
  align-items: center;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  color: white;
  border-radius: 8px;
}

.stat-icon {
  font-size: 24px;
  line-height: 1;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  line-height: 1;
  color: #262626;
}

.stat-label {
  margin-top: 4px;
  font-size: 14px;
  color: #8c8c8c;
}

.technician-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.performance-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.performance-score {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
}

.performance-detail {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
  color: #8c8c8c;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background: #fafafa;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f0f8ff;
}
</style>
